package com.dx.bs.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;


import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
@ConfigurationProperties(prefix = "taole.jwt")
public class JwtUtil {
    private String key;
    private Long expire;

    public String getToken(Map<String, Object> claims) {
        Algorithm algorithm = Algorithm.HMAC256(key);
        Date now = new Date();
        Date expireDate = new Date(now.getTime() + expire);
        return JWT
                .create()
                .withHeader(createHeader())
                .withPayload(claims)
                .withIssuedAt(now)
                .withExpiresAt(expireDate)
                .sign(algorithm);
    }

    private Map<String, Object> createHeader() {
        Map<String, Object> header = new HashMap<>();
        header.put("alg", "HS256");
        header.put("typ", "JWT");
        return header;
    }

    // 校验jwt
    public DecodedJWT decode(String token) {
        Algorithm algorithm = Algorithm.HMAC256(key);
        return JWT.decode(token);
    }

    // 校验并解析 JWT
    public String verifyToken(String token) throws JWTVerificationException {
        Algorithm algorithm = Algorithm.HMAC256(key);
        return JWT.require(algorithm)
                .build()
                .verify(token)
                .getPayload(); // 这里会自动检查签名和过期时间
    }
}
